<?php

namespace App\Http\Controllers\Pay;

use EasyWeChat\Pay\Message;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;

class WxpayController extends Controller
{
    // 付款成功回调
    /* 
        {
            "transaction_id":"1217752501201407033233368018",
            "amount":{
                "payer_total":100,
                "total":100,
                "currency":"CNY",
                "payer_currency":"CNY"
            },
            "mchid":"1230000109",
            "trade_state":"SUCCESS",
            "bank_type":"CMC",
            "promotion_detail":[...],
            "success_time":"2018-06-08T10:34:56+08:00",
            "payer":{
                "openid":"oUpF8uMuAJO_M2pxb1Q9zNjWeS6o"
            },
            "out_trade_no":"1217752501201407033233368018",
            "appid":"wxd678efh567hg6787",
            "trade_state_desc":"支付成功",
            "trade_type":"MICROPAY",
            "attach":"自定义数据",
            "scene_info":{
                "device_id":"013467007045764"
            }
        }
    */
    public function postRecharge(Request $request)
    {
        $server = app('wechat.payment')->getServer();
        $server->handlePaid(function (Message $message, \Closure $next) {
            Storage::disk('log')->prepend('wxpay/recharge-'.date('Y-m-d').'.log', date('Y-m-d H:i:s').json_encode($message));
            // 🚨🚨🚨 注意：推送信息不一定靠谱哈，请务必验证
            // 建议是拿订单号调用微信支付查询接口，以查询到的订单状态为准
            // $message->out_trade_no 获取商户订单号
            // $message->payer['openid'] 获取支付者 openid
            if($message->trade_state == "SUCCESS"){
                // 统一回调处理方法
            }
            return $next($message);
        });
        return $server->serve();
    }
}
